<template>
  <div>
    <page-main>
      <el-table :data="dataList" style="width: 100%" v-loading="dataListLoading">
        <el-table-column type="index" width="60"> </el-table-column>
        <el-table-column prop="device_no" label="设备编号">
          <template #default="scope">
            <span style="cursor: pointer">{{ scope.row.device_no }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <span v-if="(scope.row.status = 1)">正常</span>
            <span v-else-if="(scope.row.status = 2)">预警</span>
            <span v-else-if="(scope.row.status = 3)">故障</span>
            <span v-else-if="(scope.row.status = 4)">停用</span>
            <span v-else-if="(scope.row.status = 5)">报警</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="mold_name" label="设备名称"> </el-table-column>
        <!-- <el-table-column prop="unit_full_name" label="联网单位">
        </el-table-column> -->
        <el-table-column prop="update_time" label="状态变化时间">
          <template #default="scope">
            {{ $getDateTime(scope.row.update_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="安装位置"> </el-table-column>
        <!-- <el-table-column label="量值">
          <template #default="scope">
            <span v-html="scope.row.measure" v-if="scope.row.measure"></span>

          </template>
        </el-table-column> -->
        <el-table-column label="操作">
          <template #default="scope">
            <!-- <el-button size="mini" @click="editDevice(scope.row)"
              >修改</el-button
            > -->
            <!-- <el-button
              v-if="scope.row.name_id == 157 || scope.row.mold_id == 30"
              type="danger"
              size="mini"
              @click="playVideoEvent(scope.row)"
              >视频监控</el-button
            > -->
            <el-button type="info" size="mini" @click="deviceNoClick(scope.row)">上报历史</el-button>
            <div
              style="margin-top: 10px"
              v-if="scope.row.name_id == 141 || scope.row.mold_id == 28"
              @click="childDeviceEvent(scope.row)"
            >
              <el-button type="primary" size="mini">关联设备</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          :current-page="pagination.page"
          :total="total"
          :page-size="pagination.size"
          :page-sizes="pagination.sizes"
          :layout="pagination.layout"
          class="pagination"
          background
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
        />
      </div>
    </page-main>
    <el-dialog title="上报历史" v-model="reportHistory" width="70%" destroy-on-close>
      <el-row style="margin-bottom: 10px">
        <el-col :span="5">
          <div>
            <span style="margin-right: 10px">状态</span>
            <el-select v-model="reportHistoryStatus" clearable placeholder="请选择">
              <el-option v-for="item in reportHistoryOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="searchBtn">搜索</el-button>
          <el-button type="warning" @click="refreshBtn">重置</el-button>
        </el-col>
      </el-row>
      <el-table :data="deviceList" style="width: 100%" border height="50vh">
        <el-table-column prop="id" label="id" width="80" align="center"></el-table-column>
        <el-table-column prop="pos_no" label="位置编号" align="center"></el-table-column>
        <el-table-column label="发生位置" align="center">
          <template #default="scope">
            <span>{{ scope.row.device_data.pos_info || scope.row.address || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="device_no" label="设备编号" align="center"></el-table-column>
        <el-table-column prop="new_mold_name" label="设备类型" align="center"></el-table-column>
        <el-table-column prop="event_type" label="事件描述" align="center"></el-table-column>
        <el-table-column prop="yj_unit_name" label="所属单位" align="center"></el-table-column>
        <el-table-column prop="create_time" label="发生时间" width="110" align="center">
          <template #default="scope">{{ $getDateTime(scope.row.create_time) }}</template></el-table-column
        >
        <!-- <el-table-column label="量值" align="center">
          <template #default="scope">
            <span v-html="scope.row.measure"></span>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="100" align="center">
          <template #default="scope">
            <el-button size="mini" type="primary" @click="lookDetailsDevice(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @current-change="getDeviceInfo"
          v-model:currentPage="deviceTabel.page"
          :page-count="deviceTabel.total_page"
          :total="deviceTabel.total"
          background
          layout="total,prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
    </el-dialog>
    <el-dialog
      title="基本信息"
      v-model="editDeviceDialogVisible"
      width="50%"
      destroy-on-close
      @close="alarmValSettingVal = []"
    >
      <el-form>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备安装建筑">
              <el-cascader
                style="width: 200px"
                clearable
                :props="buildingFloorProps"
                v-model="buildingFloorVal"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备安装位置">
              <el-input clearable v-model="formData.address" style="width: 200px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="设备安装坐标">
              <el-input clearable v-model="formData.longitude" style="width: 120px" disabled></el-input>
              <el-input clearable v-model="formData.latitude" style="width: 120px" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="设备图片">
              <el-upload
                :action="upDataUrl + '/unit/upload/upload'"
                list-type="picture-card"
                :headers="upLoadImgHeader"
                :data="{ type: 'image' }"
                :on-success="headImgUpSuccess"
                :limit="3"
                :file-list="fileList"
                :on-remove="imgChange"
                :on-exceed="onExceed"
                accept=".jpg,.png,.jpeg"
                class="headImg"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="报警值设置">
              <el-button @click="alarmValSettingDialog = true">设置</el-button>
            </el-form-item>
          </el-col>
          <el-col>
            <div id="deviceLocationMapContainer"></div>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDeviceDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitDeviceInfo">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog v-model="yuJingBoBaoDetailsDialog" v-if="yuJingBoBaoDetailsDialog" width="70%">
      <deviceReportShow :details="details" :isAll="true"></deviceReportShow>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="yuJingBoBaoDetailsDialog = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="alarmValSettingDialog"
      width="30%"
      :close-on-click-modal="false"
      title="报警值设置"
      destroy-on-close
    >
      <div class="inputBox">
        <el-row :gutter="20">
          <el-col>
            <el-select v-model="alarmValSettingVal" multiple placeholder="请选择" @change="alarmValSettingBlurEvent">
              <el-option
                v-for="item in alarmValSettingOption"
                :key="item.name"
                :label="item.desc_short"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col>
            <div class="inputItem" v-for="item in formData.warn_data" :key="item.name">
              <h3 style="margin-right: 10px">{{ item.title }}</h3>
              <el-input style="width: 100px" clearable v-model="item.value"></el-input>
            </div>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <el-button type="primary" @click="alarmValSettingDialog = false">确 定</el-button>
      </template>
    </el-dialog>
    <!-- 子设备列表 -->
    <el-dialog v-model="childDeviceDialog" width="70%" destroy-on-close>
      <el-table :data="childDeviceData" style="width: 100%" border height="50vh">
        <el-table-column prop="id" label="ID"> </el-table-column>
        <el-table-column prop="name" label="设备名称"> </el-table-column>
        <el-table-column prop="address" label="设备地址"> </el-table-column>
        <el-table-column prop="device_no" label="设备编号"> </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button size="mini" type="primary" @click="editChildDevice(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @current-change="getChildDeviceDataLists"
          v-model:currentPage="childDeviceInfo.page"
          :page-size="childDeviceInfo.rows"
          :total="childDeviceInfo.total"
          background
          layout="total,prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
    </el-dialog>
    <!-- 子设备编辑 -->
    <el-dialog v-model="childDeviceEditDialog" width="20%" destroy-on-close>
      <el-form>
        <el-row>
          <el-col>
            <el-form-item label="设备名称">
              <el-input v-model="childDeviceEditFormData.name" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="设备地址">
              <el-input v-model="childDeviceEditFormData.address" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="childDeviceEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitChildDeviceEditFormData">确 定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="playVideoBoxDialog" width="50%" class="detailsDialog">
      <div v-if="ysyplay" style="width: 100%; height: 50vh">
        <iframe id="dplayer" :src="playingVideoUrl" style="width: 100%; height: 100%"></iframe>
      </div>
      <div v-else style="width: 100%; height: 100%">
        <dplayer :playingVideoUrl="playingVideoUrl"></dplayer>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 分页
import paginationMixin from '@/mixins/pagination'
import { setDeviceData } from '@/util/deviceData'
import dplayer from './dplayer.vue'
// 标识组件

import deviceReportShow from '@/views/xfSupervise/components/deviceReportShow.vue'

export default {
  components: {
    deviceReportShow,
    dplayer
  },
  // 分页
  mixins: [paginationMixin],
  data() {
    return {
      playingVideoUrl: '',
      dataList: [],
      dataListLoading: false,
      total: 0,
      info: {},
      editDeviceDialogVisible: false,
      details: {},
      deviceList: [],
      reportHistoryOptions: [
        { label: '预警', value: 1 },
        { label: '故障', value: 2 },
        { label: '火警', value: 3 }
      ],
      deviceTabel: [],
      yuJingBoBaoDetailsDialog: false,
      details: {},
      reportHistory: false,
      device_no: '',
      reportHistoryStatus: '',
      buildingFloorVal: [],
      formData: {
        longitude: '',
        latitude: '',
        address: '',
        building_id: '',
        floor_id: '',
        images: [],
        warn_data: [],
        id: ''
      },
      buildingFloorProps: {
        lazy: true,
        lazyLoad: this.buildingFloorLazyLoad
      },
      upDataUrl: import.meta.env.DEV ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL,
      alarmValSettingDialog: false,
      alarmValSettingVal: [],
      alarmValSettingOption: [],
      childDeviceDialog: false,
      hostDeviceNo: '',
      childDeviceData: [],
      childDeviceInfo: '',
      childDeviceEditDialog: false,
      childDeviceEditFormData: {
        id: '',
        device_no: '',
        host_device_no: '',
        name: '',
        address: ''
      },
      playVideoBoxDialog: false,
      playingVideoUrl: ''
    }
  },
  computed: {
    upLoadImgHeader() {
      return {
        'A-Token': this.$store.state.user.a_token,
        'U-Token': this.$store.state.user.u_token
      }
    }
  },
  created() {
    this.getDataList()
    this.getWarnConfig()
  },
  methods: {
    playVideoEvent(row) {
      this.$api.post('/unit/DeviceInstall/showDevice', { device_no: row.device_no }).then((res) => {
        let { video_url } = res.data

        if (!video_url) {
          this.$message.error('视频连接错误，请稍后再试')
          return false
        }
        this.playingVideoUrl = video_url
        this.playVideoBoxDialog = true
        if (res.data.factory_name == '萤石云' || res.data.factory_name == '智城') {
          this.ysyplay = true
        } else if (res.data.installer == '赋安云' || res.data.factory_name == '海康') {
          this.ysyplay = false
        }
      })
    },
    submitChildDeviceEditFormData() {
      this.$api.post('/unit/device/subSave', this.childDeviceEditFormData).then((res) => {
        this.$message.success('操作成功')
        this.childDeviceEditDialog = false
        this.getChildDeviceDataLists()
      })
    },
    editChildDevice(row) {
      this.childDeviceEditFormData = JSON.parse(JSON.stringify(row))
      this.childDeviceEditDialog = true
    },
    getChildDeviceDataLists(page) {
      let pageNum = 1
      if (page) {
        pageNum = page
      }
      this.$api
        .post('/unit/device/subLists', {
          host_device_no: this.hostDeviceNo,
          page: pageNum,
          rows: 10
        })
        .then((res) => {
          this.childDeviceData = res.data.list
          delete res.data.list
          this.childDeviceInfo = res.data
        })
    },
    childDeviceEvent(row) {
      this.hostDeviceNo = row.device_no
      this.childDeviceDialog = true
      this.getChildDeviceDataLists()
    },
    alarmValSettingBlurEvent() {
      let temp = this.alarmValSettingVal
      let data = this.alarmValSettingOption
      let tempData = []
      temp.map((val) => {
        data.map((item) => {
          if (val == item.name) {
            tempData.push({
              title: item.desc,
              value: item.value,
              name: item.name
            })
          }
        })
      })
      this.formData.warn_data = tempData
    },
    getWarnConfig() {
      this.$api.get('/unit/config/warnConfig').then((res) => {
        this.alarmValSettingOption = res.data
      })
    },
    onExceed() {
      this.$message({
        showClose: true,
        message: '如需更改，请先删除已上传的',
        type: 'error'
      })
    },
    imgChange(file) {
      let delUrl = ''
      let tempArr = []
      if (file.url.indexOf(import.meta.env.VITE_APP_API_BASEURL) + 1) {
        delUrl = file.url.split(import.meta.env.VITE_APP_API_BASEURL).join('')
      } else {
        delUrl = file.response.data.result.split(import.meta.env.VITE_APP_API_BASEURL).join('')
      }
      this.formData?.images?.map((curVal) => {
        if (curVal != delUrl) {
          tempArr.push(curVal)
        }
      })
      this.formData.images = tempArr
    },
    headImgUpSuccess(e) {
      let tempImg = this.formData?.images?.length ? this.formData.images : []
      tempImg.push(e.data.result)
      this.formData.images = tempImg
    },
    submitDeviceInfo() {
      let data = this.formData
      data.building_id = this.buildingFloorVal[0]
      data.floor_id = this.buildingFloorVal[1]
      this.$api.post('/unit/DeviceInstall/editInfo', data).then((res) => {
        this.$message.success('操作成功')
        this.getDataList()
        this.editDeviceDialogVisible = false
      })
    },
    buildingFloorLazyLoad(node, resolve) {
      if (!node.level) {
        this.$api.post('/unit/Building/lists', { rows: 99999 }).then((res) => {
          const nodes = res.data.lists.map((curVal) => ({
            value: curVal.id,
            label: curVal.architecture_name,
            leaf: node.level >= 2
          }))
          resolve(nodes)
        })
      } else {
        this.$api
          .post('/unit/BuildingFloor/lists', {
            rows: 99999,
            building_id: node.value ? node.value : this.buildingFloorVal[0]
          })
          .then((res) => {
            const nodes = res.data.lists.map((curVal) => ({
              value: curVal.id,
              label: curVal.floor_name,
              leaf: node.level >= 1
            }))
            resolve(nodes)
          })
      }
    },
    refreshBtn() {
      this.reportHistoryStatus = ''
      this.getDeviceInfo()
    },
    searchBtn() {
      this.getDeviceInfo()
    },
    //   详情
    lookDetailsDevice(row) {
      this.details = row
      this.yuJingBoBaoDetailsDialog = true
    },

    // 基本信息按钮
    editDevice(row) {
      row?.warn_data?.map((item) => {
        this.alarmValSettingVal.push(item.name)
      })
      this.buildingFloorVal = [row.building_id, row.floor_id]
      let temp = JSON.parse(JSON.stringify(row))
      let tempImg = []
      temp?.images?.map((val) => {
        tempImg.push({ url: import.meta.env.VITE_APP_API_BASEURL + val })
      })
      this.fileList = tempImg
      for (let key in this.formData) {
        this.formData[key] = temp[key]
      }
      this.formData.device_no = row.device_no
      this.editDeviceDialogVisible = true
      this.$nextTick(() => {
        this.getMap(row.longitude, row.latitude)
      })
    },
    getMap(lng, lat) {
      // 地图
      let marker = null
      let map = new AMap.Map('deviceLocationMapContainer', {
          resizeEnable: true, // 允许缩放
          center: [lng, lat], // 设置地图的中心点
          zoom: 15 // 设置地图的缩放级别，0 - 20
        }),
        doMark = (lng, lat) => {
          // 设置标记
          map && marker && map.remove(marker)
          marker = new AMap.Marker({
            map: map,
            position: new AMap.LngLat(lng, lat) // 经纬度
          })
        }
      doMark(lng, lat)
      map.on('click', (res) => {
        this.formData.longitude = res.lnglat.lng
        this.formData.latitude = res.lnglat.lat
        doMark(res.lnglat.lng, res.lnglat.lat)
      })
    },
    deviceNoClick(row) {
      this.device_no = row.device_no
      this.getDeviceInfo()
      this.reportHistory = true
    },
    // 设备上报信息
    async getDeviceInfo(page) {
      let pageNum = 1
      if (page) {
        pageNum = page
      }
      let param = {
        method: this.reportHistoryStatus,
        device_no: this.device_no,
        page: pageNum,
        rows: 10
      }
      let resp = await this.$api.post('/unit/DeviceWarning/Lists', param)
      this.deviceList = await setDeviceData(resp.data.list)
      this.deviceTabel = resp.data
    },
    // 当前记录数据
    getDataList() {
      this.dataListLoading = true
      let params = {
        rows: 12,
        page: this.pagination.page
      }
      this.$api
        .post('/unit/DeviceInstall/Lists', params)
        .then(async (res) => {
          this.dataList = await setDeviceData(res.data.list)
          this.total = res.data.total
        })
        .finally(() => {
          this.dataListLoading = false
        })
    }
  }
}
</script>

<style scoped lang="scss">
.inputBox {
  .inputItem {
    display: flex;
    align-items: center;
  }
}
.block {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
#deviceLocationMapContainer {
  width: 100%;
  height: 450px;
}
</style>
